<template>
  <el-dialog
    :model-value="visible"
    title="字段预览"
    width="90%"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <div class="preview-container">
      <table class="preview-table" border="1" cellspacing="0" cellpadding="0">
        <thead>
          <!-- 第一行：字段分类（合并相同分类，单个字段则上下合并） -->
          <tr class="category-row">
            <template v-for="(group, groupIndex) in groupedFields" :key="`group-${groupIndex}`">
              <!-- 如果分类只有一个字段，上下合并显示字段名称 -->
              <th
                v-if="group.colspan === 1"
                :rowspan="2"
                class="category-header single-field-header"
                :style="{ minWidth: getFieldMinWidth(group.fields[0]) + 'px' }"
              >
                {{ group.fields[0].fieldName }}
              </th>
              <!-- 如果分类有多个字段，只占第一行，显示分类名称 -->
              <th v-else :colspan="group.colspan" class="category-header">
                {{ group.name }}
              </th>
            </template>
          </tr>
          <!-- 第二行：字段名称（只显示多字段分类下的字段） -->
          <tr class="field-row">
            <th
              v-for="(field, index) in multiFieldHeaders"
              :key="`field-${index}`"
              class="field-header"
              :style="{ minWidth: field.minWidth + 'px' }"
            >
              {{ field.name }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in previewData" :key="rowIndex" class="data-row">
            <td v-for="(field, index) in fieldHeaders" :key="`data-${index}`" class="data-cell">
              <div class="preview-cell">
                <!-- 枚举类型：显示选项列表 -->
                <template v-if="field.fieldType === 5">
                  <div class="enum-options-list">
                    <div
                      v-for="(option, optIndex) in field.enumOptions"
                      :key="optIndex"
                      class="enum-option-item"
                    >
                      {{ option }}
                    </div>
                  </div>
                </template>
                <!-- 计算公式：显示公式信息 -->
                <template v-else-if="field.hasFormula">
                  <div class="formula-display">
                    <div class="formula-text">{{ getFormulaDisplay(field) }}</div>
                    <!-- <div
                      class="formula-fields"
                      v-if="field.formulaFields && field.formulaFields.length"
                    >
                      <div class="formula-field-label">使用的字段：</div>
                      <div class="formula-field-list">
                        <span
                          v-for="(formulaField, fIndex) in field.formulaFields"
                          :key="fIndex"
                          class="formula-field-item"
                        >
                          {{ formulaField }}
                          <span v-if="fIndex < field.formulaFields.length - 1">、</span>
                        </span>
                      </div>
                    </div> -->
                  </div>
                </template>
                <!-- 其他类型：显示示例数据 -->
                <template v-else>
                  {{ row[field.fieldEnglishName] }}
                </template>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  fieldList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible'])

// 处理字段列表，按分类分组（保持顺序）
const groupedFields = computed(() => {
  const groups = []
  let currentCategory = null
  let currentGroup = null

  props.fieldList.forEach((field) => {
    const category = field.fieldCategory || ''
    // 如果分类相同，合并到当前组
    if (category === currentCategory) {
      currentGroup.fields.push(field)
      currentGroup.colspan++
    } else {
      // 新建一个组
      currentCategory = category
      currentGroup = {
        name: category || '未分类',
        fields: [field],
        colspan: 1
      }
      groups.push(currentGroup)
    }
  })

  return groups
})

// 生成字段表头（包含所有字段，用于数据行）
const fieldHeaders = computed(() => {
  const headers = []
  props.fieldList.forEach((field) => {
    headers.push({
      name: field.fieldName,
      fieldEnglishName: field.fieldEnglishName,
      fieldType: field.fieldType,
      enumOptions: field.enumOptions || [],
      hasFormula: field.isFormula || false,
      formula: field.formula || '',
      formulaFields: getFormulaFields(field),
      minWidth: getFieldMinWidth(field)
    })
  })
  return headers
})

// 生成多字段分类的表头（第二行只显示这些字段）
const multiFieldHeaders = computed(() => {
  const headers = []
  props.fieldList.forEach((field) => {
    // 检查该字段所属的分类是否有多个字段
    const category = field.fieldCategory || ''
    const group = groupedFields.value.find((g) => {
      const gCategory = g.name === '未分类' ? '' : g.name
      return (
        gCategory === category &&
        g.fields.some((f) => f.fieldEnglishName === field.fieldEnglishName)
      )
    })

    // 只包含多字段分类下的字段
    if (group && group.colspan > 1) {
      headers.push({
        name: field.fieldName,
        fieldEnglishName: field.fieldEnglishName,
        fieldType: field.fieldType,
        enumOptions: field.enumOptions || [],
        hasFormula: field.isFormula || false,
        formula: field.formula || '',
        formulaFields: getFormulaFields(field),
        minWidth: getFieldMinWidth(field)
      })
    }
  })
  return headers
})

// 获取公式使用的字段
function getFormulaFields(field) {
  if (!field.isFormula || !field.formula) {
    return []
  }

  const formula = field.formula
  const operators = ['+', '-', '*', '/']
  const fields = []

  // 从公式中提取字段中文名
  let formulaStr = formula
  operators.forEach((op) => {
    formulaStr = formulaStr.replace(new RegExp('\\' + op, 'g'), ',')
  })

  const parts = formulaStr
    .split(',')
    .map((p) => p.trim())
    .filter((p) => p)
  parts.forEach((part) => {
    // 根据中文名查找字段
    const fieldObj = props.fieldList.find((f) => f.fieldName === part)
    if (fieldObj) {
      fields.push(fieldObj.fieldName)
    }
  })

  return fields
}

// 获取公式显示文本
function getFormulaDisplay(field) {
  if (!field.formula) {
    return ''
  }

  // 公式直接使用中文名，直接返回
  return field.formula
}

// 根据字段类型获取最小宽度
function getFieldMinWidth(field) {
  if (!field) return 100

  // 如果是字段对象
  if (field.fieldType !== undefined) {
    if (field.fieldType === 5) {
      // 枚举类型需要更多空间显示选项
      return 150
    }
    if (field.isFormula) {
      // 计算公式需要更多空间
      return 120
    }
    return 100
  }

  // 如果是字段类型值
  if (field === 5) {
    return 150
  }
  return 100
}

// 生成预览数据（示例数据）
const previewData = computed(() => {
  const row = {}
  props.fieldList.forEach((field) => {
    row[field.fieldEnglishName] = getPreviewValue(field)
  })
  return [row]
})

// 根据字段类型生成预览值
function getPreviewValue(field) {
  switch (field.fieldType) {
    case 1: // 两位小数
      return '9.99'
    case 2: // 整数
      return '1'
    case 3: // 日期
      return '2020-01-01'
    case 4: // 文本
      return '文本'
    case 5: // 枚举
      return '' // 枚举类型在模板中单独处理
    default:
      return '-'
  }
}

// 关闭弹窗
function handleClose() {
  emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
.preview-container {
  width: 100%;
  overflow-x: auto;
}

.preview-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;

  thead {
    background: #f5f7fa;

    .category-row {
      .category-header {
        padding: 6px 12px;
        text-align: center;
        font-weight: 500;
        color: #606266;
        border: 1px solid #ebeef5;
        background: #f5f7fa;

        &.single-field-header {
          white-space: nowrap;
        }
      }
    }

    .field-row {
      .field-header {
        padding: 6px 12px;
        text-align: center;
        font-weight: 500;
        color: #606266;
        border: 1px solid #ebeef5;
        background: #f5f7fa;
        white-space: nowrap;
      }
    }
  }

  tbody {
    .data-row {
      .data-cell {
        padding: 6px 12px;
        text-align: center;
        border: 1px solid #ebeef5;
        vertical-align: middle;
      }
    }
  }
}

.preview-cell {
  min-height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.enum-options-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-start;
  width: 100%;
}

.enum-option-item {
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
}

.formula-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  // width: 100%;
}

.formula-text {
  font-weight: 500;
  color: #409eff;
  font-size: 14px;
}

.formula-fields {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.formula-field-label {
  font-weight: 500;
}

.formula-field-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.formula-field-item {
  color: #606266;
}
</style>
